package com.example.security.distributed.uaa.dao;

import com.example.security.distributed.uaa.model.PermissionDto;
import com.example.security.distributed.uaa.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhuyaotong
 * @date 2021/6/1
 */
@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据账号查询用户信息
     *
     * @param username
     * @return
     */
    public UserDto getUserByUsername(String username) {

        String sql = "select id,username,password,fullname,mobile from t_user where username = ?";

        // 连接数据库查询用户
        List<UserDto> list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));

        if (list != null && list.size() == 1) {
            return list.get(0);
        }

        return null;
    }

    /**
     * 根据用户 id 查询用户权限
     *
     * @param userId
     * @return
     */
    public List<String> findPermissionByUserId(String userId) {

        String sql = "select * from t_permission where id IN(" +
                "select permission_id from t_role_permission where role_id IN(" +
                "select role_id from t_user_role where user_id = ?))";

        // 连接数据库查询权限
        List<PermissionDto> list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(PermissionDto.class));

        List<String> permissions = new ArrayList<>();

        list.forEach(c -> permissions.add(c.getCode()));

        return permissions;
    }

}
